/**
 * Copyright (C) 2009 Matteo Merli <mm@merlimat.org>
 * 
 * $Id: JavaMethod.java 23 2009-01-14 16:45:36Z matteo.merli $
 * $URL: http://pxl-lang.googlecode.com/svn/trunk/src/main/java/pxl/types/JavaMethod.java $
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *         http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package pxl.types;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import pxl.errors.PxlException;
import pxl.errors.TypeError;
import pxl.types.annotations.Exported;
import pxl.types.annotations.Parameters;
import pxl.types.util.FunctionCall;
import pxl.types.util.PxlArgument;
import pxl.types.util.PxlParametersList;

public class JavaMethod extends PxlObject
{

    private final String name;

    private final Method method;

    private final PxlParametersList parameters;

    public JavaMethod( Method method )
    {
        this.name = method.getName();
        this.method = method;

        if ( method.isAnnotationPresent( Parameters.class ) )
        {
            parameters = PxlParametersList.getFromAnnotations( method
                    .getAnnotation( Parameters.class ) );
        }
        else
        {
            // Get parameter from method definition
            parameters = PxlParametersList.getFromJavaMethod( method );
        }
    }

    @Override
    public String getType()
    {
        return "JavaMethod";
    }

    public Method getInternalMethod()
    {
        return method;
    }

    @Override
    @Exported
    public PxlString __repr__()
    {
        StringBuilder sb = new StringBuilder();
        sb.append( '<' ).append( getType() );
        sb.append( ' ' ).append( name );
        sb.append( " @ " ).append( hashCode() );
        sb.append( '>' );
        return new PxlString( sb.toString() );
    }

    // Operators

    @Override
    public PxlObject __call__( List<PxlArgument> args )
    {
        return __call__( null, args );
    }

    public PxlObject __call__( PxlObject self, List<PxlArgument> args )
    {
        Object[] values = FunctionCall.getArgumentValues( name, parameters,
                args );

        Object res;
        try
        {
            res = method.invoke( self, values );
        }
        catch ( PxlException pe )
        {
            throw pe;
        }
        catch ( IllegalAccessException iae )
        {
            throw new TypeError( "Illegal access: " + iae );
        }
        catch ( InvocationTargetException ite )
        {
            if ( ite.getCause() instanceof PxlException )
                throw (PxlException) ite.getCause();

            throw new TypeError( "Invocation target exception: "
                    + ite.getCause() );
        }
        catch ( IllegalArgumentException e )
        {
            throw new TypeError( "Illegal arguments: " + e );
        }

        if ( res == null )
        {
            res = None.instance();
        }
        // else if ( !(res instanceof PxlObject) )
        // {
        // return ConversionFactory.convertFromJava( res );
        // }

        // returned object is already a PxlObject
        return (PxlObject) res;
    }

    // Attributes

    private static final Map<String, PxlObject> attrs = PxlObject
            .getExportedMethods( JavaMethod.class );

    @Override
    protected PxlObject getAttribute( String name )
    {
        return attrs.get( name );
    }

    @Override
    protected Collection<String> getAttributeNames()
    {
        return attrs.keySet();
    }

}
